<template>
  <px-dialog v-model="visible" width="80%" @close="cancel">
    <template #header>
      <div class="header">
        <span class="text">选择培训课程</span>
        <span class="tip">
          <px-icon size="16" color="#faad14"> <Warning /></px-icon>推荐使用MP4和PDF格式课程文件
        </span>
      </div>
    </template>
    <div v-loading="loading" class="select-container">
      <div class="left-container">
        <px-tree
          ref="treeRef"
          :data="treeData"
          node-key="id"
          highlight-current
          default-expand-all
          :current-node-key="currentNode"
          :expand-on-click-node="false"
          @node-click="nodeClick"
        >
          <template #default="{ node }">
            <span class="custom-tree-node show-hide">
              <span>
                <FolderIcon class="folder-icon" />
                {{ node.label }}
              </span>
            </span>
          </template>
        </px-tree>
      </div>
      <div class="right-container">
        <px-table
          ref="tableRef"
          height="500"
          :data="tableData"
          size="small"
          border
          class="common-table"
          @selection-change="tableSelect"
          @select="selectClick"
        >
          <px-table-column type="selection" fixed width="55" prop="selection" align="center" />
          <px-table-column prop="name" label="文件名" min-width="180" show-overflow-tooltip>
            <template #default="scope">
              <div class="row-fileName">
                <FolderIcon v-if="scope.row.docType === 'F'" class="file-icon" />
                <FileIcon v-if="scope.row.docType === 'D'" class="file-icon" />
                <span>{{ scope.row.name }}</span>
              </div>
            </template>
          </px-table-column>
          <px-table-column prop="fileSize" label="文件大小" min-width="80" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.fileSize !== null ? formatBytes(scope.row.fileSize) : "" }}
            </template>
          </px-table-column>
          <px-table-column prop="updateByName" label="修改人" min-width="80" show-overflow-tooltip />
          <px-table-column prop="updateTime" label="修改时间" min-width="100" show-overflow-tooltip />
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="pageNum"
          v-model:limit="pageSize"
          class="table-pagination"
          :total="total"
          @pagination="getTableData"
        />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancel">取消</px-button>
        <px-button type="primary" @click="confirm">确定</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup>
import { ref, reactive, toRefs, computed, onMounted, nextTick } from "vue";
import { loadTreeAPI, searchDocAPI } from "@/api/knowledge/documentManage";
import FolderIcon from "@/assets/svg/knowledge/folder.svg?component";
import FileIcon from "@/assets/svg/knowledge/file.svg?component";
import { formatBytes } from "@/views/all/knowledge/utils";

const emits = defineEmits(["update:visible", "select"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const treeRef = ref(null);
const tableRef = ref(null);
const state = reactive({
  loading: false,
  treeData: [],
  tableData: [],
  tableSelectedData: [],
  total: 0,
  pageNum: 1,
  pageSize: 20,
  currentNode: null
});
const { loading, treeData, tableData, total, pageNum, pageSize, currentNode } = toRefs(state);

onMounted(() => {
  getTreeData();
});

const formatNull = data => {
  return data.map(node => {
    node.label = node.name;
    if (node.children == null) {
      node.children = []; // 将children属性为null的替换为空数组
    } else {
      node.children = formatNull(node.children); // 递归处理子节点
    }
    return node;
  });
};

// const byteToMb = bytes => {
//   return (bytes / 1024 / 1024).toFixed(2);
// };

// 获取左侧文件夹树数据
const getTreeData = async () => {
  try {
    const params = {
      type: "manage", // manage：全部文件，favorite：我的收藏，upload：我的上传
      name: ""
    };
    state.loading = true;
    const res = await loadTreeAPI(params);
    state.treeData = formatNull([res]);
    nextTick(() => {
      state.currentNode = state.treeData[0].id;
      treeRef.value.setCurrentKey(state.currentNode.id);
      getTableData();
    });
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

// 获取右侧表格数据
const getTableData = async () => {
  try {
    state.loading = true;
    const params = {
      id: state.currentNode,
      type: "manage",
      pageNum: state.pageNum,
      pageSize: state.pageSize
    };
    const res = await searchDocAPI(params);
    let data = [];
    if (Array.isArray(res.data) && res.data?.length > 0) {
      data = res.data?.filter(item => {
        const nameAry = item?.name?.split(".") || [];
        const type = nameAry[nameAry?.length - 1] || "";
        const suffix = type?.toLowerCase();
        if (item.docType !== "F" && ["mp4", "pdf"].includes(suffix)) {
          return item;
        }
      });
    }
    state.total = data?.length;
    state.tableData = data;
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

// 点击树节点
const nodeClick = async (data, node, obj) => {
  state.currentNode = data.id;
  getTableData();
};

const tableSelect = val => {
  state.tableSelectedData = val;
};

const selectClick = (selection, row) => {
  if (selection.length > 1) {
    let del_row = selection.shift();
    tableRef.value.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
  }
};

const cancel = () => {
  emits("update:visible", false);
};

const confirm = async () => {
  emits("select", state.tableSelectedData);
};
</script>

<style lang="scss" scoped>
.header {
  display: flex;
  align-items: center;

  .text {
    margin-right: 10px;
  }
}

.tip {
  display: inline-flex;
  align-items: center;
  font-size: 12px;
  color: rgb(170 170 170);
}

.select-container {
  position: relative;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  width: 100%;
  height: 600px;
  background-color: #fff;
  border-radius: 8px;

  .left-container {
    width: 316px;
    height: 100%;
    overflow-y: auto;
    border: 1px solid #dfdfdf;
    border-radius: 4px;
  }

  .right-container {
    width: calc(100% - 316px);
    height: 100%;
    padding-left: 18px;
  }
}

.folder-icon {
  display: inline-block;
  vertical-align: middle;
}

.tree-icon-container {
  .tree-icon {
    display: inline-block;
    margin: 8px 0 0 8px;
    font-size: 12px;
  }
}

.row-fileName {
  display: flex;
  align-items: center;

  .file-icon {
    margin-right: 8px;
  }
}
</style>
